package com.liuyi.netty.im.lychat.modular.controller;


import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liuyi.netty.im.commons.codes.CodeConst;
import com.liuyi.netty.im.lychat.config.base.BaseQueryController;
import com.liuyi.netty.im.lychat.modular.controller.model.UserFriendModel;
import com.liuyi.netty.im.lychat.modular.controller.model.UserFriendModel.Result;
import com.liuyi.netty.im.lychat.modular.entity.UserFriend;
import com.liuyi.netty.im.lychat.modular.service.IGroupMemberService;
import com.liuyi.netty.im.lychat.modular.service.IUserFriendService;
import com.liuyi.netty.im.lychat.modular.service.IUserService;
import com.liuyi.netty.im.server.util.ImHelp;
import com.liuyi.rapid.develop.tool.resp.RespCall;
import com.liuyi.rapid.develop.tool.resp.Response;
import com.liuyi.rapid.develop.tool.resp.ResponseCall;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.hibernate.validator.constraints.Length;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.liuyi.rapid.develop.tool.resp.ResponseCall.success;
import static org.springframework.http.ResponseEntity.ok;

/**
 * <p>
 * 用户好友表 前端控制器
 * </p>
 *
 * @author mybatis-plus
 * @since 2021-12-29
 */
@Api(value = "", tags = {"用户好友表"})
@RestController
@RequestMapping("/modular/user-friend")
@Validated
public class UserFriendController implements BaseQueryController<UserFriend, IUserFriendService> {

    @Resource
    private IUserFriendService userFriendService;
    @Resource
    private IGroupMemberService groupMemberService;
    @Resource
    private IUserService userServicel;

    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", dataType = "string", name = "friendUserId", value = "好友id"),
            @ApiImplicitParam(paramType = "path", dataType = "string", name = "memo", value = "修改的备注")
    })
    @ApiOperation(value = "修改备注", notes = "", httpMethod = "POST")
    @PostMapping("/modifyMemo/{friendUserId}/memo/{memo}")
    public ResponseEntity<Response<Void>> modifyMemo(@PathVariable String friendUserId,
                                                     @PathVariable @Length(max = 12, message = "备注不可超过12个字符") String memo) {
        String userId = StpUtil.getLoginIdAsString();
        QueryWrapper<UserFriend> queryWrapper = q().eq(UserFriend.FRIEND_USER_ID, friendUserId).eq(UserFriend.USER_ID, userId);
        if (server().count(queryWrapper) <= 0) {
            return RespCall.error("抱歉，未找到该好友，请刷新后重试");
        }
        server().update(new UserFriend().setFriendMemo(memo), queryWrapper);
        server().cache().removeUserIdAndFriendUserId(userId, friendUserId);
        return ok(ResponseCall.<Void>successMsg("修改成功").okShow());
    }

    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", dataType = "string", name = "groupId", value = "群组id")
    })
    @ApiOperation(value = "好友列表（和群组关联查询）", notes = "", httpMethod = "GET")
    @GetMapping("/groupFriend/{groupId}")
    public ResponseEntity<Response<List<UserFriendModel.GroupFriendResult>>> groupFriend(@PathVariable String groupId) {
        List<UserFriend> userFriends = server().list(q().eq(UserFriend.USER_ID, StpUtil.getLoginIdAsString()));
        List<UserFriendModel.GroupFriendResult> results = new ArrayList<>(userFriends.size());
        userFriends.forEach(item -> {
            wrapper(item);
            UserFriendModel.GroupFriendResult r = new UserFriendModel.GroupFriendResult();
            r.setGroupMemberIs(groupMemberService.cache().countByUserIdAndGroupId(item.getFriendUserId(), groupId) > 0);
            r.setUserFriend(item);
            results.add(r);
        });
        return ok(success(results));
    }

    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", dataType = "string", name = "friendUserId", value = "好友id")
    })
    @ApiOperation(value = "删除好友", notes = "", httpMethod = "POST")
    @PostMapping("/delFriend/{friendUserId}")
    public ResponseEntity<Response<String>> delFriend(@PathVariable String friendUserId) {
        server().delFriend(StpUtil.getLoginIdAsString(), friendUserId);
        return ok(ResponseCall.success("删除成功",ImHelp.sessionId(CodeConst.SessionType.C2C, friendUserId)).okShow());
    }

    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", dataType = "string", name = "userId", value = "用户id")
    })
    @ApiOperation(value = "好友查询", notes = "", httpMethod = "GET")
    @GetMapping("/getFriend/{userId}")
    public ResponseEntity<Response<Result>> getFriend(@PathVariable String userId) {
        UserFriend userFriend = server().getOne(q().eq(UserFriend.USER_ID, StpUtil.getLoginIdAsString()).eq(UserFriend.FRIEND_USER_ID, userId).last("limit 1"));
        Result result = new Result();
        result.setFriend(userFriend != null);
        result.setUserFriend(userFriend);
        result.setUser(userServicel.cache().getById(userId));
        return ok(success(result));
    }

    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", dataType = "string", name = "friendUserId", value = "好友id")
    })
    @ApiOperation(value = "新增好友", notes = "", httpMethod = "POST")
    @PostMapping("/add/{friendUserId}")
    public ResponseEntity<Response<String>> add(@PathVariable String friendUserId) {
        server().createFriend(StpUtil.getLoginIdAsString(), friendUserId);
        return ok(success(ImHelp.sessionId(CodeConst.SessionType.C2C, friendUserId)));
    }

    @Override
    public IUserFriendService server() {
        return userFriendService;
    }

    @Override
    public void pre(QueryWrapper<UserFriend> wrapper, String method) {
        wrapper.eq(UserFriend.USER_ID, StpUtil.getLoginIdAsString());
    }

    @Override
    public void wrapper(UserFriend data) {
        server().wrapper(data);
    }
}

